package com.zz.input;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.util.HashMap;
import java.util.Map;

import com.zz.input.Keys.Key;

public class InputHandler implements KeyListener, MouseListener, MouseWheelListener {
	private Map<Integer, Key> mappings = new HashMap<Integer, Key>();
	
	public InputHandler(Keys keys) {
		mappings.put(KeyEvent.VK_UP, keys.up);
		mappings.put(KeyEvent.VK_DOWN, keys.down);
		mappings.put(KeyEvent.VK_LEFT, keys.left);
		mappings.put(KeyEvent.VK_RIGHT, keys.right);

		mappings.put(KeyEvent.VK_W, keys.up);
		mappings.put(KeyEvent.VK_S, keys.down);
		mappings.put(KeyEvent.VK_A, keys.left);
		mappings.put(KeyEvent.VK_D, keys.right);

		mappings.put(MouseEvent.BUTTON1, keys.fire);
		mappings.put(MouseEvent.BUTTON2, keys.use);
	}

	public void keyPressed(KeyEvent ke) {
		toggle(ke, true);
	}

	public void keyReleased(KeyEvent ke) {
		toggle(ke, false);
	}

	public void keyTyped(KeyEvent ke) {
	}

	private void toggle(KeyEvent ke, boolean state) {
		Key key = mappings.get(ke.getKeyCode());
		if (key != null) {
			key.nextState = state;
		}
	}
	
	private void toggle(MouseEvent ke, boolean state) {
		Key key = mappings.get(ke.getButton());
		if (key != null) {
			key.nextState = state;
		}
	}
	
	@Override
	public void mouseWheelMoved(MouseWheelEvent e) {
		Keys.wheelRotation = e.getWheelRotation();	
	}

	@Override
	public void mouseClicked(MouseEvent e) {}
	@Override
	public void mouseEntered(MouseEvent e) {}
	@Override
	public void mouseExited(MouseEvent e) {}

	@Override
	public void mousePressed(MouseEvent e) {
		toggle(e, true);
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		toggle(e, false);
	}
}
